<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
      fixed
      placeholder
    />
    <!-- 搜索栏 -->
    <van-search
      v-model.trim="key"
      @input="onInput"
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      @search="onSearch(key)"
    >
      <template #action>
        <div @click="goSearch(key)">搜索</div>
      </template>
    </van-search>

    <!-- 历史记录 -->
    <van-cell-group v-if="!key">
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item, index) in historyList"
        :key="index"
        @click="$router.push({ name: 'result', query: { key: item } })"
      >
        {{ item }}
      </van-cell>
    </van-cell-group>

    <!-- 关联区域 -->
    <van-cell-group v-else>
      <van-cell
        v-for="(item, index) in suggestList"
        :key="index"
        :title="item"
        icon="search"
        @click="goSuggest(item)"
      />
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI } from "@/api";
export default {
  data() {
    return {
      key: "",
      suggestList: [],
      timerID: null,
      historyList: JSON.parse(window.localStorage.getItem("history")) || [],
    };
  },
  methods: {
    // 联动请求
    onInput() {
      // 判断有没有值,有值才请求
      if (this.key) {
        // 清除计时器
        clearTimeout(this.timerID);
        // 防抖
        this.timerID = setTimeout(async () => {
          let res = await suggestAPI({
            q: this.key,
          });
          // console.log(res);
          this.suggestList = res.data.data.options;
        }, 1000);
      }
    },

    onSearch(key) {
      // 调用这串代码
      this.goSearch(key);
      // 判断本次搜索在不在数组里,不在就保存
      if (this.historyList.indexOf(this.key) == -1) {
        // 把key加入到数组中
        this.historyList.unshift(this.key);
        // 保存到本地存储
        window.localStorage.setItem(
          "history",
          JSON.stringify(this.historyList)
        );
      }
    },
    goSearch(key) {
      // 跳转路由
      this.$router.push({
        path: "/search/result",
        query: {
          key,
        },
      });
    },

    goSuggest(item) {
      this.key = item;
      // 跳转路由
      this.$router.push({
        path: "/search/result",
        query: {
          key: this.key,
        },
      });
    },
  },
};
</script>

<style>
</style>